<?php
/**
 * 体检报告
 *
 * User: kaikaic
 * Date: 2018/12/2
 * Time: 15:30
 */

namespace app\exam\model;

use app\exam\service\AccountService;
use app\exam\service\OrderService;
use app\exam\service\ReportService;
use service\ExcelService;
use service\ToolsService;

class ReportModel {

    /**
     * 读取EXCEL文件数据
     */
    public function readExcelFile($excelFile) {
        $excelFile = env('root_path') . $excelFile;
        $excelData = ExcelService::importExcel($excelFile);
        if (!$excelData) {
            return 0;
        }

        $importCount = 0;
        for ($i=0; $i<count($excelData); $i++) {
            $tmp = $excelData[$i];
            if (count($tmp) != 4) {
                continue;
            }

            $params = array();
            $params['user_name'] = trim($tmp[0]);
            $params['mobile'] = trim($tmp[1]);
            $params['order_sn'] = trim($tmp[2]);
            $params['name'] = trim($tmp[3]);

            // 数据记录
            $rs = $this->doImport($params);
            if ($rs) {
                $importCount++;
            }
        }

        return $importCount;
    }

    /**
     * 导入实现
     *
     * @param $data
     * @return bool
     */
    private function doImport($data) {
        $data = $this->excelDataFilter($data);
        if (!$data) {
            return false;
        }

        // 帐号是否存在
        $mobile = $data['mobile'];
        $account = AccountService::getInstance()->single(array('mobile'=>$mobile));
        if (!$account) {
            return false;
        }

        // 订单号是否存在
        $orderSN = $data['order_sn'];
        $order = OrderService::getInstance()->single(array('order_sn'=>$orderSN));
        if (!$order) {
            return false;
        }

        // 订单状态是否正常
        if (!OrderService::getInstance()->checkOrderFinished($order)) {
            return false;
        }

        $record = ReportService::getInstance()->single(array('mobile'=>$mobile, 'order_sn'=>$data['order_sn']));
        if ($record) {
            return false;
        }
        $orderstatus['order_status'] = 4;
        $orderstatus['update_time'] = time();
        OrderService::getInstance()->update($orderstatus,$orderSN,'order_sn');

        $params = array();
        $params['name'] = $data['name'];
        $params['mobile'] = $mobile;
        $params['order_sn'] = $data['order_sn'];
        $params['account_id'] = $account['id'];
        $params['real_name'] = $account['real_name'];
        $params['identity_card'] = $account['identity_card'];
        $params['create_time'] = time();

        return ReportService::getInstance()->insert($params);
    }

    /**
     * 对excel数据过滤
     */
    private function excelDataFilter($data) {
        if (!$data['name'] || !$data['mobile'] || !$data['order_sn']) {
            return array();
        }

        if (!ToolsService::checkMobile($data['mobile'])) {
            return array();
        }

        return $data;
    }
}

